package com.bosssoft.trainee.controller;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.auth0.jwt.JWT;
import com.bosssoft.trainee.common.CodeMsg;
import com.bosssoft.trainee.common.Result;
import com.bosssoft.trainee.entity.po.User;
import com.bosssoft.trainee.service.RoleService;
import com.bosssoft.trainee.service.TokenService;
import com.bosssoft.trainee.service.UserService;
import com.bosssoft.trainee.until.JwtUntil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqiang
 * @date 2022/7/5 9:34
 * 判断登录是否成功
 */
@RestController
@Slf4j
public class IndexController {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    TokenService tokenService;


    @GetMapping("/login")
    public Result<Object> login(User user, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        //获取用户账号密码
        User userForBase = new User();
        userForBase.setUserId(userService.findByUserAccount(user).getUserId());
        userForBase.setUserAccount(userService.findByUserAccount(user).getUserAccount());
        userForBase.setUserPassword(userService.findByUserAccount(user).getUserPassword());
        //判断账号或密码是否正确
        if (!userForBase.getUserPassword().equals(user.getUserPassword())) {
            return Result.error(CodeMsg.USER_OR_PASS_ERROR);
        } else {
            String token = JwtUntil.getToken(userForBase);
            try {
//                jsonObject.put过时，改用set
                jsonObject.set("token", token);
                //获取菜单
                jsonObject.set("menu", userService.getMenu(userForBase.getUserId()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Cookie cookie = new Cookie("token", token);
            log.info("cookie信息:{}", cookie.getValue());
            cookie.setPath("/");
            response.addCookie(cookie);

            //参数1：key值、参数2：value值、参数3：过期时间、参数4：时间单位
            stringRedisTemplate.opsForValue().set(userForBase.getUserId().toString(), token, 1, TimeUnit.HOURS);
            log.info("redis信息：{}", stringRedisTemplate.opsForValue().get(userForBase.getUserId().toString()));
            return Result.success(jsonObject);
        }
    }

    /**
     * 登出
     *
     * @return result
     */
    @GetMapping("/logout")
    public Result<Object> logout() {
        stringRedisTemplate.delete(tokenService.getUserId());
        return Result.success("退出登录成功！");
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/user/info")
    public Result<Object> getUserInfo(String token) {
        String userId = JWT.decode(token).getAudience().get(0);
        if (userId != null) {
            Map<String, Object> map = new HashMap<>();
            User user = userService.findUserById(Integer.valueOf(userId));
//            map.put("roles", user.getUserAccount());
            String[] roles = new String[1];
            //获取角色id
            roles[0] = roleService.getRoleIdByName(user.getUserRole()).getRoleId().toString();
//            map.put("roles", '['+roleService.getRoleIdByName(user.getUserRole()).getRoleId().toString()+']');
            map.put("roles", roles);
            map.put("name", user.getUserName());
            map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            map.put("introduction", "introduction");
            map.put("roleName", roleService.getRoleIdByName(user.getUserRole()).getRoleName());
            map.put("userId", user.getUserId());
            return Result.success(map);
        }else {
            return Result.error(CodeMsg.USER_NOT_EXSIST);
        }
    }


}
